import 'package:boss/common/common.dart';
import 'package:boss/main.dart';
import 'package:boss/models/coupon.dart';
import 'package:boss/models/store_group_info.dart';
import 'package:boss/provider/login_user_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/marketing/coupon/couponList/modal/coupon_share_posters_modal.dart';
import 'package:boss/ui/widget/custom_divier.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:provider/provider.dart';

Future<void> showCouponShareModal(BuildContext context, Coupon coupon) {
  return showModalBottomSheet(
    context: context,
    builder: (ctx) => _CouponShareModal(coupon),
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(10.0),
        topRight: Radius.circular(10.0),
      ),
    ),
  );
}

class _CouponShareModal extends StatefulWidget {
  final Coupon coupon;

  const _CouponShareModal(this.coupon);

  @override
  __CouponShareModalState createState() => __CouponShareModalState();
}

class __CouponShareModalState extends State<_CouponShareModal> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      left: false,
      right: false,
      top: false,
      child: Container(
        height: 340.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(topLeft: Radius.circular(10.w)),
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  _ShareBtn(
                    icon: 'assets/image/share_wx.png',
                    title: '微信好友',
                    onTap: () async {
                      final storeGroupInfo = await getStoreGroupInfo();
                      if (storeGroupInfo == null) return;
                      Navigator.pop(context);
                      fluwx.shareToWeChat(
                        fluwx.WeChatShareMiniProgramModel(
                          webPageUrl: 'https://baidu.com',
                          userName: storeGroupInfo.orgAppId,
                          path: formatShareUrl(storeGroupInfo.appletUrl, 0),
                          miniProgramType: environment == env.prod ? fluwx.WXMiniProgramType.RELEASE : fluwx.WXMiniProgramType.PREVIEW,
                          title: widget.coupon.shareTitle,
                          description: widget.coupon.couponName,
                          thumbnail: fluwx.WeChatImage.network(widget.coupon.shareImageUrl),
                        ),
                      );
                    },
                  ),
                  _ShareBtn(
                    icon: 'assets/image/share_qr.png',
                    title: '查看二维码',
                    onTap: () async {
                      final storeGroupInfo = await getStoreGroupInfo();
                      if (storeGroupInfo == null) return;
                      Navigator.pop(context);

                      showCouponSharePostersModal(context, formatShareUrl(storeGroupInfo.appletUrl, 1));
                    },
                  ),
                ],
              ),
            ),
            CustomDivider(
              margin: EdgeInsets.symmetric(horizontal: 75.w),
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              behavior: HitTestBehavior.translucent,
              child: Container(
                height: 100.w,
                alignment: Alignment.center,
                child: Text(
                  '取消',
                  style: TextStyleConstant().origin_32,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<StoreGroupInfo> getStoreGroupInfo() async {
    try {
      showLoadingToast();

      final loginUserProvider = Provider.of<LoginUserProvider>(context, listen: false);
      final storeGroupInfoRes = await api.queryStoreGroupInfo(loginUserProvider.loginUser.storeId);
      if (!storeGroupInfoRes.successful()) {
        throw storeGroupInfoRes.msg;
      }
      if (storeGroupInfoRes?.data?.orgAppId == null) {
        throw '小程序暂未开放';
      }

      return storeGroupInfoRes.data;
    } catch (e) {
      toast(e.toString());
      return null;
    } finally {
      hideLoadingToast();
    }
  }

  String formatShareUrl(String appletUrl, int type) {
    final loginUserProvider = Provider.of<LoginUserProvider>(context, listen: false);

    if (type == 0) {
      //小程序
      return '/pagesSubA/couponShare/index?waiterId=${loginUserProvider.loginUser.userId}&shareUserId=${loginUserProvider.loginUser.userId}&shareSource=boss&couponTemplateId=${widget.coupon.id}';
    } else {
      //二维码
      return '$appletUrl&page=/pagesSubA/couponShare/index&waiterId=${loginUserProvider.loginUser.userId}&shareUserId=${loginUserProvider.loginUser.userId}&shareSource=boss&couponTemplateId=${widget.coupon.id}';
    }
  }

  shareWx(fluwx.WeChatScene scene) async {
    final storeGroupInfo = await getStoreGroupInfo();
    if (storeGroupInfo == null) return;
    Navigator.pop(context);

    CouponShareUtil.widget2Unit8List(context, formatShareUrl(storeGroupInfo.appletUrl, 1), (value) {
      final source = fluwx.WeChatImage.binary(value);
      fluwx.shareToWeChat(fluwx.WeChatShareImageModel(source, scene: scene));
    });
  }
}

class _ShareBtn extends StatelessWidget {
  final String icon;
  final String title;
  final VoidCallback onTap;

  const _ShareBtn({
    @required this.icon,
    @required this.title,
    this.onTap,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.translucent,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          BaseImage(
            icon,
            width: 110.w,
            height: 110.w,
          ),
          Container(
            margin: EdgeInsets.only(top: 20.w),
            child: Text(
              title,
              style: TextStyleConstant().normal_3_24,
            ),
          ),
        ],
      ),
    );
  }
}
